package fi.laurea.mp3player;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Vector;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

import com.google.gson.Gson;

import fi.laurea.jsonbus.Receiver;
import fi.laurea.jsonbus.ReceiverListener;
import fi.laurea.jsonbus.Sender;

import javazoom.jl.player.Player;

public class MP3Player implements ReceiverListener {

	private String[] filelist = new String[] {};
	private Player player;
	private Receiver receiver;
	private Sender sender;
	private Gson gson;

	public MP3Player() {
		this.gson = new Gson();
		this.receiver = new Receiver("MP3Player", "TestPlayer", this);
		this.sender = new Sender("MP3Player");

	}

	public void play(String filename) {
		try {
			File file = new File("media/" + filename);
			AudioInputStream in = AudioSystem.getAudioInputStream(file);
			AudioInputStream din = null;
			AudioFormat baseFormat = in.getFormat();
			AudioFormat decodedFormat = new AudioFormat(
					AudioFormat.Encoding.PCM_SIGNED,
					baseFormat.getSampleRate(), 16, baseFormat.getChannels(),
					baseFormat.getChannels() * 2, baseFormat.getSampleRate(),
					false);
			din = AudioSystem.getAudioInputStream(decodedFormat, in);
			// Play now.
			rawplay(decodedFormat, din);
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String[] getFilelist() {

		String[] ret;
		Vector<String> temp = new Vector<String>();

		File folder = new File("media");

		File[] listOfFiles = folder.listFiles();

		for (int i = 0; i < listOfFiles.length; i++) {
			if (listOfFiles[i].isFile()) {
				temp.add(listOfFiles[i].getName());

			}

		}
		ret = new String[temp.size()];

		int i = 0;
		for (String s : temp) {
			ret[i] = s;
			i++;
		}
		return ret;
	}

	public static void main(String[] args) {
		MP3Player player = new MP3Player();

	}

	private void rawplay(AudioFormat targetFormat, AudioInputStream din)
			throws IOException, LineUnavailableException {
		byte[] data = new byte[4096];
		SourceDataLine line = getLine(targetFormat);
		if (line != null) {
			// Start
			line.start();
			int nBytesRead = 0, nBytesWritten = 0;
			while (nBytesRead != -1) {
				nBytesRead = din.read(data, 0, data.length);
				if (nBytesRead != -1)
					nBytesWritten = line.write(data, 0, nBytesRead);
			}
			// Stop
			line.drain();
			line.stop();
			line.close();
			din.close();
		}
	}

	private SourceDataLine getLine(AudioFormat audioFormat)
			throws LineUnavailableException {
		SourceDataLine res = null;
		DataLine.Info info = new DataLine.Info(SourceDataLine.class,
				audioFormat);
		res = (SourceDataLine) AudioSystem.getLine(info);
		res.open(audioFormat);
		return res;
	}

	@Override
	public void prosessGloballMessage(String json) {
		// TODO Auto-generated method stub

	}

	@Override
	public void prosessPrivateMessage(String json) {
		InstructionMessage message = (InstructionMessage)gson.fromJson(json, InstructionMessage.class);
		
		
		if(message.isSendFilelist()){
			
			FilelistMessage fileListMessage = new FilelistMessage();
			fileListMessage.setFilelist(this.getFilelist());
			
			sender.sendToId(fileListMessage, message.getReturnID());
		}
		
		else{
			this.play(message.getFilename());
		}
		
	}
}
